package com.base.andlangcore.http.gson

import com.google.gson.Gson
import com.google.gson.JsonParser
import com.google.gson.TypeAdapter
import okhttp3.ResponseBody
import retrofit2.Converter
/**
 * 返回的报文 json解析
 * 以及报文特定json字段转换指定的字段名称
 */
class GsonResponseBodyConverter <T>(
    private val gson: Gson?,
    private val adapter: TypeAdapter<T>?
) :
    Converter<ResponseBody, T> {

    @Throws(Exception::class)
    override fun convert(value: ResponseBody): T? {
        val jsonobject = JsonParser.parseString(value.string()).asJsonObject
        value.use {
            var result: T? = null
            if (jsonobject.isJsonObject) {
                result = when {
                    jsonobject.has("resp_code") -> {
                        jsonobject.add("code", jsonobject.get("resp_code"))
                        jsonobject.add("message", jsonobject.get("resp_message"))
                        jsonobject.add("data", jsonobject.get("result"))
                        adapter?.fromJson(jsonobject.toString())
                    }
                    jsonobject.has("recode") -> {
                        jsonobject.add("code", jsonobject.get("recode"))
                        jsonobject.add("message", jsonobject.get("remsg"))
                        jsonobject.add("data", jsonobject.get("redata"))
                        adapter?.fromJson(jsonobject.toString())
                    }
                    else -> {
                        adapter?.fromJson(jsonobject.toString())
                    }
                }
            } else {
                result = adapter?.fromJson(jsonobject.toString())
            }
            return result
        }
    }
}